class TumblrApi
  @client = nil
  @last_like = nil
  attr_accessor :client

  def initialize
    @client = Tumblr::Client.new
    @last_like = 0
  end

  def follow_blogs
    blogs = get_blogs
    (BLOGS - blogs).each_with_index do |blog, index|
      TumblrFollowWorker.perform_in((((25 * index).seconds).from_now), blog)
    end
    @client.info
  end

  def transfer_likes
    (TURNEDTHEFUCKON - LIKES).each_with_index do |post, index|
      self.like(post[:id], post[:reblog_key], ((25 * index)))
    end
  end

  def like(post_id, reblog_key, seconds)
    TumblrLikeWorker.perform_in(seconds.seconds.from_now, post_id, reblog_key)
  end

  def get_likes(blog)
    total = @client.blog_likes(blog)['liked_count']
    liked_posts = []
    liked_posts << likes_group(blog, @last_like)
    @last_like += 21
    (total/20).times do
      liked_posts << likes_group(blog, @last_like)
      @last_like += 20
    end
    all_likes = liked_posts.flatten.map { |post| {id: post['id'], reblog_key: post['reblog_key']} }
    File.open("#{Rails.root}/config/initializers/#{blog}.rb", 'w') { |file| file.write("#{blog.upcase} = #{all_likes.to_s}") }
  end

  def get_blogs
    last = 0
    total = @client.following['total_blogs']
    blogs = []
    blogs << @client.following['blogs'].map { |b| b['url'] }
    last += 21
    (total/20).times do
      blogs << @client.following(offset: last)['blogs'].map { |b| b['url'] }
      last += 20
    end
    blogs.flatten
  end

  def my_likes
    total = @client.likes['liked_count']
    liked_posts = []
    liked_posts << @client.likes['liked_posts']
    @last_like += 21
    (total/20).times do
      liked_posts << @client.likes(offset: @last_like)['liked_posts']
      @last_like += 20
    end
    all_likes = liked_posts.flatten.map { |post| {id: post['id'], reblog_key: post['reblog_key']} }
    File.open("#{Rails.root}/config/initializers/likes.rb", 'w') { |file| file.write("LIKES = #{all_likes.to_s}") }
  end

  def unlikes
    TURNEDTHEFUCKON.each_with_index do |post, index|
      TumblrUnlikeWorker.perform_in((25 * index).seconds.from_now, post[:id], post[:reblog_key])
    end
  end

  private

  def likes_group(blog, offset)
    @client.blog_likes(blog, offset: offset)['liked_posts']
  end
end